package edu.neusoft.android.yuejian14.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.List;

import edu.neusoft.android.yuejian14.R;
import edu.neusoft.android.yuejian14.activity.TrainDetailActivity;
import edu.neusoft.android.yuejian14.javabean.Train;

import static edu.neusoft.android.yuejian14.Const_Pic.BASE_URL;


public class TrainListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;
    private List<Train> mDataList;
    private LayoutInflater mLayoutInflater;
    private  int train_id;
    public TrainListAdapter(Context mContext, List<Train> mDataList) {
        this.mContext = mContext;
        this.mDataList = mDataList;
        mLayoutInflater = LayoutInflater.from(mContext);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = mLayoutInflater.inflate(R.layout.item_cardview, parent, false);
        return new ViewHolder(mContext, v);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if (mDataList == null || mDataList.isEmpty()) {
            return;
        }

        final Train entity = mDataList.get(position);

        if (null == entity) {
            return;
        }

        ViewHolder viewHolder = (ViewHolder) holder;
        viewHolder.setView(entity);
        viewHolder.itemView.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                Intent intent = new Intent(mContext, TrainDetailActivity.class);
                intent.putExtra("trainid",entity.getTrainid());
        mContext.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDataList == null ? 0 : mDataList.size();
    }

    public void setData(List<Train> list) {
        this.mDataList = list;
        notifyDataSetChanged();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        private static ImageView train_pic;
        Context mContext;
        TextView train_name;

        public ViewHolder(Context context, View itemView) {
            super(itemView);
            mContext = context;
            train_name = (TextView) itemView.findViewById(R.id.name);
            train_pic = (ImageView) itemView.findViewById(R.id.pic);
        }


        void setView(Train entity) {
            train_name.setText(entity.getTrainname());
            String train_pic = BASE_URL  + entity.getTrainpic();
            if (!train_pic.equals("")) {
                Picasso.with(mContext).load(train_pic).error(R.drawable.no_pic).into(ViewHolder.train_pic);
            }

        }

    }
}
